package buss.console.util;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Iterator;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.params.ConnRouteParams;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.w3c.dom.Document;

import com.base.common.SysParam;

public class HttpUtil {
	 private static Logger log = Logger.getLogger(HttpUtil.class);
	 
	 public static String httpGet(String url){
		 log.info("http请求url: "+url+"开始");
		 String result=null;
		 GetMethod getMethod = new GetMethod(url);
		 HttpClient hc = new HttpClient();
//		 hc.getHostConfiguration().setProxy("10.191.113.100", 80);
//		 hc.getParams().setAuthenticationPreemptive(true);
//		 hc.getState().setProxyCredentials(AuthScope.ANY, new UsernamePasswordCredentials("c_liuyang-098", "!QAZ2wsx"));
		// 设置连接超时时间
		hc.getHttpConnectionManager().getParams().setConnectionTimeout(60 * 1000);
		// 设置读取超时时间
		hc.getHttpConnectionManager().getParams().setSoTimeout(120 * 1000);
		try {
			//请求http状态，200 成功  
			int httpStatus = hc.executeMethod(getMethod);
			if(200 == httpStatus){
				log.info("请url:"+url+"响应状态正常");
				result=getMethod.getResponseBodyAsString();
				log.info("请求响应结果result: "+result);
				return result;
			}else{
				log.info("请url:"+url+"响应状态异常,httpStatus: "+httpStatus);
				return result;
			}
		} catch (HttpException e) {
			log.info("请url:"+url+"发生错误："+e);
			log.error(HttpUtil.class, e);
		} catch (IOException e) {
			log.info("请url:"+url+"发生错误");
			log.error(HttpUtil.class, e);
		}finally{
				getMethod.releaseConnection();
		}
		return result;
	 }

	 /**
	  * 
	  * HttpClient提交表单
	  * 
	  * @param url
	  * @param param
	  * @param charSet
	  * @return 
	  */
	 @SuppressWarnings("rawtypes")
	public static String sendByPost(String url, Map param,String charSet){
		 HttpClient httpclient = null;
		 PostMethod method = null;
		 String result = "";
		 InputStreamReader rs = null;
		 BufferedReader bs = null;
		 try {
		    httpclient = new HttpClient();
		    method = new PostMethod(url);
		    if(param != null && !param.isEmpty()){
		    int len = param.size();
		    method.setRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=utf-8");
		    NameValuePair[] np = new NameValuePair[len];
		    Iterator iter = param.keySet().iterator();
		    int i = 0;
		    while(iter.hasNext()){
		        String k = (String)iter.next();
		        String v = (String)param.get(k) ;
		        np[i]=new NameValuePair();
		        np[i].setName(k);
		        np[i].setValue(v);
		        i++;
		    }
		    method.setRequestBody(np);
		 }
	   httpclient.executeMethod(method);
	   //result = method.getResponseBodyAsString();
	   rs =  new InputStreamReader(method.getResponseBodyAsStream(), charSet);
	   bs = new BufferedReader(rs);
	   String line = "";
	   while((line = bs.readLine()) != null){
	       result += line;
	   }
	   log.info("HttpsUtil-sendByPost-url=" + url + "-result=" + result);
	  } catch(Exception ex){
		  log.error("接口请求异常1：" + ex);
		  result = "error\tcrm error " + ex.toString();
		  log.error("HttpsUtil-sendByPost-url=" + url + "-result=" + ex.toString());
	  } finally{
		  if(bs != null){
			  try {
				bs.close();
			} catch (IOException e) {
				log.error(e);
			}
		  }
		  if(rs != null){
			  try {
				rs.close();
			} catch (IOException e) {
				log.error(e);
			}
		  }
		  if(method != null){
			  	method.releaseConnection();
		  }
	  }
	  return result;
	 }
	 
	 /**
	  * 
	  * HttpClient发送json
	  * 
	  * @param url
	  * @param content
	  * @param charSet
	  * @return
	  */
	 public static String sendByPost(String url, String content, String charSet) {
		 log.info("接口请求路径：" + url);
		 HttpPost post = new HttpPost(url);
			HttpEntity se;
			String retSrc = "";
			try {
				se = new StringEntity(content);
//				se = new StringEntity(content, charSet);
				post.setEntity(se);
				//启用代理
				//HttpResponse httpResponse = getHttpClient().execute(post);
				//不启用代理
				HttpResponse httpResponse = new DefaultHttpClient().execute(post);
				retSrc = EntityUtils.toString(httpResponse.getEntity());
			} catch (UnsupportedEncodingException e) {
				log.error("接口请求异常1：" + e);
			} catch (ClientProtocolException e) {
				log.error("接口请求异常2：" + e);
			} catch (IOException e) {
				log.error("接口请求异常3：" + e);
			}
			log.info("接口返回结果：" + retSrc);
			return retSrc;
		}
	 
	 /**
	  * get请求
	  * 
	  * @param url
	  * @param charSet
	  * @return
	  */
	 public static String sendByGet(String url, String charSet){
		 HttpClient httpclient = null;
		 GetMethod method = null;
		 String result = "";
		 InputStreamReader rs = null;
		 BufferedReader bs = null;
		 try {
			 httpclient = new HttpClient();
			 method = new GetMethod(url);
			 httpclient.executeMethod(method);
			 rs =  new InputStreamReader(method.getResponseBodyAsStream(), charSet);
			   bs = new BufferedReader(rs);
			 String line = "";
	     	 while((line = bs.readLine()) != null){
	     		 result += line;
		     }
		  } catch(Exception ex){
			  result = "error\tcrm error " + ex.toString();
			  log.error(ex);
		  } finally{
			  if(bs != null){
				  try {
					bs.close();
				} catch (IOException e) {
					log.error(e);
				}
			  }
			  if(rs != null){
				  try {
					rs.close();
				} catch (IOException e) {
					log.error(e);
				}
			  }
			  if(method != null){
				  method.releaseConnection();
			  }
		  }
		  return result;
	 }
	 
	 
	 public static String sendByPost(String url, byte[] xmlData, String charSet) {
			DataInputStream input = null;
			ByteArrayOutputStream out = null;
			try {
				// 获得到位置服务的链接
				URL urlStr = new URL(url);
				URLConnection urlCon = urlStr.openConnection();
				urlCon.setDoOutput(true);
				urlCon.setDoInput(true);
				urlCon.setUseCaches(false);
				// 将xml数据发送到位置服务
				urlCon.setRequestProperty("Content-Type", "text/xml");
				urlCon.setRequestProperty("Content-length",
						String.valueOf(xmlData.length));
				DataOutputStream printout = new DataOutputStream(
						urlCon.getOutputStream());
				printout.write(xmlData);
				printout.flush();
				printout.close();
				input = new DataInputStream(urlCon.getInputStream());
				byte[] rResult;
				out = new java.io.ByteArrayOutputStream();
				byte[] bufferByte = new byte[256];
				int l = -1;
				int downloadSize = 0;
				while ((l = input.read(bufferByte)) > -1) {
					downloadSize += l;
					out.write(bufferByte, 0, l);
					out.flush();
				}
				rResult = out.toByteArray();
				DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
				DocumentBuilder db = dbf.newDocumentBuilder();
				Document d = db.parse(new ByteArrayInputStream(rResult));
				String TaskAddr = d.getElementsByTagName("TaskAddr").item(0)
						.getFirstChild().getNodeValue();
				return TaskAddr;
			} catch (Exception e) {
				log.error(e);
				return null;
			} finally {
				if(out != null){
					try {
						out.close();
						input.close();
					} catch (Exception ex) {
						log.error(ex);
					}
				}
			}
		}
		
	 /**
	  * 
	  * HttpClient 配置代理服务器
	  * 
	  * 
	  * @return
	  */
	 public static DefaultHttpClient getHttpClient() {
		 DefaultHttpClient httpClient = new DefaultHttpClient();
		 //String proxyHost = SysParam.getSysParam("local.proxyHost");
		 String proxyHost = SysParam.getSysParam("ipaddress04");
		 int proxyPort = Integer.parseInt(SysParam.getSysParam("local.proxyPort"));
		 String userName = SysParam.getSysParam("local.userName");
		 String password = SysParam.getSysParam("local.password");
		 httpClient.getCredentialsProvider().setCredentials(
				 new AuthScope(proxyHost, proxyPort),
				 new UsernamePasswordCredentials(userName, password));
		 HttpHost proxy = new HttpHost(proxyHost,proxyPort);
		 httpClient.getParams().setParameter(ConnRouteParams.DEFAULT_PROXY, proxy);
		 return httpClient;
		}
	 	/**
	 	 * 推送优享汇数据(发放,核销)请求
	 	 * 
	 	 * @author c_shenmengnan
	 	 * @date 2017年12月6日 上午10:07:14
	 	 * @version 1.0
	 	 *
	 	 * @param url 请求连接
	 	 * @param params 请求参数
	 	 * @param headers 请求头
	 	 * @return 返回信息
	 	 * @throws Exception
	 	 */
	 public static String postClubString(String url, Map<String,String> params, Map<String,String> headers) throws Exception {
 		HttpClient httpclient = null;
 		PostMethod method = null;
 		String result = "";
 		InputStreamReader rs = null;
 		BufferedReader bs =  null;
 		try {
			httpclient = new HttpClient();
			method = new PostMethod(url);
			// 设置请求参数
			if(params != null){
				int len = params.size();
				NameValuePair[] nameValuePairs = new NameValuePair[len];
				int i = 0;
				for (String name : params.keySet()) {
					nameValuePairs[i]=new NameValuePair();
					nameValuePairs[i].setName(name);
					nameValuePairs[i].setValue(params.get(name));
					i++;
				}
				method.setRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=utf-8");
				method.setRequestBody(nameValuePairs);
				// 设置header头信息
				if(headers != null){
					for (String name : headers.keySet()) {
						method.setRequestHeader(name, headers.get(name));
					}  
				}
			}
			httpclient.executeMethod(method);
			rs = new InputStreamReader(method.getResponseBodyAsStream(), "UTF-8");
			bs = new BufferedReader(rs);
			String line = "";
			while((line = bs.readLine()) != null){
				result += line;
			}
		} catch (Exception e) {
			log.error("HttpsUtil.postClubString-url="+url+",error:"+e.toString(),e);
			throw e;
		}finally{
			if(bs != null){
				try {
					bs.close();
				} catch (IOException e) {
					log.error("HttpsUtil.postClubString-bs:"+e.toString(),e);
				}
			}if(rs != null){
				try {
					rs.close();
				} catch (IOException e) {
					log.error("HttpsUtil.postClubString-rs:"+e.toString(),e);
				}
			}
			if(method != null){
				method.releaseConnection();
			}
		}
 		return result;
 	}
	 
	 public static String httpPostByJson(String url, String content, String charSet) {
			String retSrc = "";
			try {
				HttpPost post = new HttpPost(url);
				StringEntity se = new StringEntity(content, charSet);
				se.setContentEncoding(charSet);
				se.setContentType("application/json");
				post.setEntity(se);
				HttpResponse httpResponse = new DefaultHttpClient().execute(post);
				retSrc = EntityUtils.toString(httpResponse.getEntity(),charSet);
			} catch (UnsupportedEncodingException e) {
				log.error(e);
			} catch (ClientProtocolException e) {
				log.error(e);
			} catch (IOException e) {
				log.error(e);
			}
			return retSrc;
		 }
}
